package com.zero.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zero.account.entity.AccountEntity;
import com.zero.account.mapper.AccountMapper;
import com.zero.account.service.AccountService;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;


/**
 * @author zero
 * @ClassName AccountServiceImpl
 * @Description
 * @Date 2025/5/15 13:37
 */
@Service
public class AccountServiceImpl implements AccountService {
    private final AccountMapper mapper;

    public AccountServiceImpl(AccountMapper accountMapper) {
        this.mapper = accountMapper;
    }


    @GlobalTransactional
    @Override
    public void deduct(String userId, int money) {
        mapper.deduct( userId, money);
    }

    @GlobalTransactional
    @Override
    public void refund(String userId, int money) {
        mapper.refund( userId, money);
    }
    /**
     * 账户充值
     */
     public void recharge(String userId, int money) {
          // 查询账户信息
         AccountEntity account =  mapper.selectOne(new QueryWrapper<AccountEntity>().eq("user_id", userId));
         if( account == null){
             account =  new AccountEntity();
              account.setId(System.nanoTime());
              account.setUserId(userId);
               account.setMoney(money);
                mapper.insert(account);
         }else{
              account.setMoney(account.getMoney() + money);
              mapper.updateById(account);
         }
     }
    /**
     *  账户查询
     */
     public AccountEntity query(String userId) {
          return mapper.selectOne(new QueryWrapper<AccountEntity>().eq("user_id", userId));
     }
}
